/**
 * Copyright(c) by JNet Smartware Group.
 * All rights reserved. Not distribution or redistribution without
 * any permission of JNet Smartware Group.
 * 
 * @author thuc
 * 2010/05/22
 * Program: SWTFoodSearch.java
 */
package vn.smartware.co.client.search;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.TableTree;
import org.eclipse.swt.custom.TableTreeItem;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;

import vn.smartware.co.commons.Const;
import vn.smartware.co.commons.SWTUtils;
import vn.smartware.co.dto.MstFoodDTO;
import vn.smartware.co.dto.MstPriceDTO;
import vn.smartware.co.framework.common.BaseConstant;
import vn.smartware.co.framework.exception.ClientException;
import vn.smartware.co.framework.exception.FatalException;
import vn.smartware.co.framework.form.CommonSearchForm;
import vn.smartware.co.framework.plugin.LangResources;
import vn.smartware.co.framework.swt.base.JNetShell;
import vn.smartware.co.framework.utils.MsgBoxUtils;
import vn.smartware.co.java.net.commons.Utils;

/**
 * SWTFoodSearch
 * @author thuctt
 */
@SuppressWarnings({"rawtypes","deprecation"})
public class SWTFoodSearch extends JNetShell { 

	private static Log log = LogFactory.getLog(SWTFoodSearch.class);
	
	private TableTree tableTree;
	
	private Combo cmbCurrency;

	private Text txtPriceE;

	private Text txtPriceS;
	
	private Text txtSearchName;

	private Button btnSearch;

	private Text txtNoEnd;

	private Text txtNoStart;

	private Group grpSearch;

	private Button btnClose;

	private Button btnClear;

	private Table tblInfo;

	private CLabel clblMessage;

	private Button btnSelect;

	private static final int SIZE_X = 585;

	private static final int SIZE_Y = 560;

	private static final int TBL_ROW_COUNT = 14;
	
	/**
	 * Constructor
	 * @param parent
	 */
	public SWTFoodSearch(Shell parent) {
		super(parent, LangResources.getText("SWTFoodSearch.shell"), new Point(SIZE_X, SIZE_Y));
	}
	
	/* (non-Javadoc)
	 * @see vn.smartware.co.framework.swt.base.JNetShell#displaySearchCriteria()
	 */
	@Override
	protected void displaySearchCriteria() {
		if (!Utils.isNullEmpty(this.getSearchCriteria())){
			CommonSearchForm form = (CommonSearchForm)this.getSearchCriteria();
			if (!Utils.isNullEmpty(form.getNoStart())){
				txtNoStart.setText(form.getNoStart());
			}
			if (!Utils.isNullEmpty(form.getNoEnd())){
				txtNoEnd.setText(form.getNoEnd());
			}
		}
		//
		try {
			if (!initData()) {
				lockScreen(true);
				return;
			}
		} catch (FatalException e) {
			log.error("FatalException.", e);
			fatalErrorMsgBox();
		}
	}

	/**
	 * get initialize data
	 *
	 */
	@SuppressWarnings("unchecked")
	private boolean initData() throws FatalException {

		Map map = new HashMap();
		map.put(Const.SYSTEM_CONFIG.MONEY_TYPE, Boolean.TRUE);
//		map = SWTUtils.ComboProcess.getComboInitItems(map, this);
		
		String[] items = (String[])map.get(Const.SYSTEM_CONFIG.MONEY_TYPE);
		if (items == null || items.length == 0 || Utils.isNullEmpty(items[1])){
			MsgBoxUtils.errorMsgBox("errors.COMBO_DATA_NOT_SET", 
					new Object[]{LangResources.getText("SWTFoodSearch.cmbCurrency")});
			return false;
		}
		cmbCurrency.setItems(items);
			
		return true;
	}

	/**
	 * clearAction
	 */
	protected void clearAction() {
		
		SWTUtils.OperatorUI.clearAll(this.getChildren());
		SWTUtils.OperatorUI.setEnableAll(grpSearch.getChildren(), true);
		Control[] infoGrp = new Control[]{
				tblInfo,
				btnSelect
		};
		SWTUtils.OperatorUI.setEnableAll(infoGrp, false);
		txtNoStart.setFocus();
	}

	/**
	 * displayAction
	 */
	protected void displayAction() {
		
		try {
			if (!chkInput()){
				return;
			}
			
			CommonSearchForm form = new CommonSearchForm();
			form.setActionForm("commonSearchForm");
			form.setActionMethod("getFoodList");
			
			form.setNoStart(Utils.toEmpty(txtNoStart.getText()));
			form.setNoEnd(Utils.toEmpty(txtNoEnd.getText()));
			form.setSearchName(txtSearchName.getText());
			form.setPriceStart(Utils.toNormalNumber(txtPriceS.getText()));
			form.setPriceEnd(Utils.toNormalNumber(txtPriceE.getText()));
			form.setCurrencyCd(SWTUtils.ComboProcess.getSelectingValue(cmbCurrency));
			form.setName(Utils.toEmpty(txtSearchName.getText()));
			
			form = (CommonSearchForm)execute(form);
			
			if (form.getList().isEmpty()){
				MsgBoxUtils.warningMsgBox("warning.NO_DATA_FOUND");
				txtNoStart.setFocus();
				return;
			}
			
			displayTable(form.getList());
			
			Control[] infoGrp = new Control[]{
					tblInfo,
					btnSelect
			};
			SWTUtils.OperatorUI.setEnableAll(infoGrp, true);
			tblInfo.setSelection(0);
			tblInfo.setFocus();
			
			String msg = Integer.toString(form.getList().size());
			msg += " " + MsgBoxUtils.getMessage("info.ROWS", new Object[]{});
			clblMessage.setText(msg);
			
		} catch (ClientException e) {
			log.error("ClientException.", e);
			fatalErrorMsgBox();
		} catch (FatalException e) {
			log.error("FatalException.", e);
			fatalErrorMsgBox();
		}
	}

	/**
	 * check input data
	 * @return boolean
	 */
	private boolean chkInput() throws ClientException {
		
		if (!SWTUtils.Check.checkNumeric(txtNoStart, 
				LangResources.getText("SWTFoodSearch.lblSearchNo"))){
			return false;
		}
		
		if (!SWTUtils.Check.checkNumeric(txtNoEnd, 
				LangResources.getText("SWTFoodSearch.lblSearchNo"))){
			return false;
		}
		
		if (!Utils.isNullEmpty(txtNoStart.getText()) && !Utils.isNullEmpty(txtNoEnd.getText())) {
			int noS = Integer.parseInt(Utils.toNormalNumber(txtNoStart.getText()));
			int noE = Integer.parseInt(Utils.toNormalNumber(txtNoEnd.getText()));
			if (noS > noE){
				MsgBoxUtils.errorMsgBox("errors.NUMBER_GREATER_COMPARE", 
						new Object[]{LangResources.getText("SWTFoodSearch.lblSearchNo"),
									LangResources.getText("SWTFoodSearch.lblSearchNo")
									});
				txtNoStart.setFocus();
				return false;
			}
		}
		
		if (!SWTUtils.Check.checkNumeric(txtPriceS, 
				LangResources.getText("SWTFoodSearch.lblPrice"))){
			return false;
		}
		
		if (!SWTUtils.Check.checkNumeric(txtPriceE, 
				LangResources.getText("SWTFoodSearch.lblPrice"))){
			return false;
		}
		
		if (!Utils.isNullEmpty(txtPriceS.getText()) && !Utils.isNullEmpty(txtPriceE.getText())) {
			int noS = Integer.parseInt(Utils.toNormalNumber(txtPriceS.getText()));
			int noE = Integer.parseInt(Utils.toNormalNumber(txtPriceE.getText()));
			if (noS > noE){
				MsgBoxUtils.errorMsgBox("errors.NUMBER_GREATER_COMPARE", 
						new Object[]{LangResources.getText("SWTFoodSearch.lblPrice"),
									LangResources.getText("SWTFoodSearch.lblPrice")
									});
				txtPriceS.setFocus();
				return false;
			}
		}
		
		return true;
	}

	/**
	 * set data to table
	 * @param list
	 */
	private void displayTable(ArrayList list) {

		tblInfo.removeAll();
		
		int rowcount = TBL_ROW_COUNT;
		if (list.size() >= rowcount){
			rowcount = list.size() + 2;
		}
		for (int i = 0; i < rowcount; i++) {
			TableTreeItem parent = new TableTreeItem(tableTree, SWT.NONE);
			parent.setBackground(BaseConstant.COLOR_TABLE_ROW_EVEN);
			
			if (i < list.size()){
				MstFoodDTO food = (MstFoodDTO)list.get(i);
				
				int idx = 0;
				parent.setText(idx++, food.getName());			//drink name
				parent.setText(idx++, "");						//price
				parent.setText(idx++, "");						//unit
				parent.setText(idx++, food.getDescription());	//description
				
				parent.setData(Const.ITEMID, food);
				
				ArrayList priceList = food.getPriceList();
				for (int j = 0; j < priceList.size(); j++) {
					MstPriceDTO price = (MstPriceDTO)priceList.get(j);
					TableTreeItem child = new TableTreeItem(parent, SWT.NONE);
					
					idx = 0;
					child.setText(idx++, "");									//drink
					child.setText(idx++, Utils.formatDouble(price.getPrice()));	//price
					String unit = "";
					if (!Utils.isNullEmpty(price.getMoneyTypeName())
							&& !Utils.isNullEmpty(food.getUnitName())){
						unit += price.getMoneyTypeName() + "/" + food.getUnitName();;
					}
					child.setText(idx++, unit);									//unit
					child.setText(idx++, "");									//type
					
					child.setData(Const.ITEMID, food);
				}
				
				//Expand the parent item
				parent.setExpanded(true);
			}
		}
	}

	/**
	 * Create contents of the dialog
	 */
	protected void initialize() { 

		grpSearch = new Group(this, SWT.NONE);
		grpSearch.setBounds(20, 14, 540, 120);
		grpSearch.setBackground(BaseConstant.COLOR_BGR_BASE);

		final CLabel lblSearchNo = new CLabel(grpSearch, SWT.CENTER | SWT.BORDER);
		lblSearchNo.setFont(BaseConstant.FONT_BASE_LABEL);
		lblSearchNo.setBounds(20, 20, 100, 22);
		lblSearchNo.setText(LangResources.getText("SWTFoodSearch.lblSearchNo"));

		txtNoStart = new Text(grpSearch, SWT.BORDER | SWT.RIGHT);
		txtNoStart.setTextLimit(3);
		txtNoStart.setFont(BaseConstant.FONT_BASE_TEXT);
		txtNoStart.setBackground(BaseConstant.COLOR_TEXT_NORMAL);
		txtNoStart.setBounds(125, 20, 120, 22);

		final Label lbl1 = new Label(grpSearch, SWT.CENTER);
		lbl1.setFont(BaseConstant.FONT_BASE_LABEL);
		lbl1.setBackground(BaseConstant.COLOR_BGR_BASE);
		lbl1.setBounds(251, 24, 22, 18);
		lbl1.setText("-");

		txtNoEnd = new Text(grpSearch, SWT.BORDER | SWT.RIGHT);
		txtNoEnd.setTextLimit(3);
		txtNoEnd.setTabs(2);
		txtNoEnd.setFont(BaseConstant.FONT_BASE_TEXT);
		txtNoEnd.setBackground(BaseConstant.COLOR_TEXT_NORMAL);
		txtNoEnd.setBounds(279, 20, 120, 22);

		final CLabel lblSearchName = new CLabel(grpSearch, SWT.CENTER | SWT.BORDER);
		lblSearchName.setBounds(20, 48, 100, 22);
		lblSearchName.setFont(BaseConstant.FONT_BASE_LABEL);
		lblSearchName.setText(LangResources.getText("SWTFoodSearch.lblSearchName"));

		txtSearchName = new Text(grpSearch, SWT.BORDER);
		txtSearchName.setBounds(125, 48, 274, 22);
		txtSearchName.setTextLimit(30);
		txtSearchName.setTabs(3);
		txtSearchName.setFont(BaseConstant.FONT_BASE_TEXT);
		txtSearchName.setBackground(BaseConstant.COLOR_TEXT_NORMAL);

		final CLabel lblPrice = new CLabel(grpSearch, SWT.CENTER | SWT.BORDER);
		lblPrice.setBounds(20, 76, 100, 22);
		lblPrice.setFont(BaseConstant.FONT_BASE_LABEL);
		lblPrice.setText(LangResources.getText("SWTFoodSearch.lblPrice"));

		txtPriceS = new Text(grpSearch, SWT.BORDER | SWT.RIGHT);
		txtPriceS.setBounds(125, 76, 120, 22);
		txtPriceS.setTextLimit(11);
		txtPriceS.setFont(BaseConstant.FONT_BASE_TEXT);
		txtPriceS.setBackground(BaseConstant.COLOR_TEXT_NORMAL);
		txtPriceS.addFocusListener(new FocusAdapter() {
			public void focusLost(final FocusEvent arg0) {
				if (!Utils.isNumeric(Utils.toNormalNumber(txtPriceS.getText()))){
					log.warn("Input string is not a number.");
					return;
				}
				txtPriceS.setText(Utils.formatDouble(txtPriceS.getText()));
			}
			public void focusGained(final FocusEvent arg0) {
				txtPriceS.setText(Utils.toNormalNumber(txtPriceS.getText()));
			}
		});

		final Label lbl1_1 = new Label(grpSearch, SWT.CENTER);
		lbl1_1.setBounds(251, 80, 22, 18);
		lbl1_1.setFont(SWTResourceManager.getFont("Microsoft Sans Serif", 10, SWT.NONE));
		lbl1_1.setBackground(SWTResourceManager.getColor(234, 234, 234));
		lbl1_1.setText("-");

		txtPriceE = new Text(grpSearch, SWT.BORDER | SWT.RIGHT);
		txtPriceE.setBounds(279, 76, 120, 22);
		txtPriceE.setTextLimit(11);
		txtPriceE.setFont(BaseConstant.FONT_BASE_TEXT);
		txtPriceE.setBackground(BaseConstant.COLOR_TEXT_NORMAL);
		txtPriceE.addFocusListener(new FocusAdapter() {
			public void focusLost(final FocusEvent arg0) {
				if (!Utils.isNumeric(Utils.toNormalNumber(txtPriceE.getText()))){
					log.warn("Input string is not a number.");
					return;
				}
				txtPriceE.setText(Utils.formatDouble(txtPriceE.getText()));
			}
			public void focusGained(final FocusEvent arg0) {
				txtPriceE.setText(Utils.toNormalNumber(txtPriceE.getText()));
			}
		});

		btnSearch = new Button(grpSearch, SWT.NONE);
		btnSearch.setBounds(416, 20, 100, 23);
		btnSearch.setFont(SWTResourceManager.getFont("Microsoft Sans Serif", 10, SWT.NONE));
		btnSearch.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
		btnSearch.setText(LangResources.getText("btnSearch"));
		btnSearch.addFocusListener(new FocusAdapter() {
			public void focusGained(final FocusEvent arg0) {
				clblMessage.setText("");
			}
		});
		btnSearch.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				displayAction();
			}
		});
		
		setDefaultButton(btnSearch);

		cmbCurrency = new Combo(grpSearch, SWT.READ_ONLY);
		cmbCurrency.setBounds(416, 76, 70, 24);
		cmbCurrency.setTextLimit(200);
		cmbCurrency.setFont(SWTResourceManager.getFont("Microsoft Sans Serif", 10, SWT.NONE));

		final Label line1 = new Label(this, SWT.HORIZONTAL | SWT.SEPARATOR);
		line1.setBounds(0, 145, 585, 15);
		line1.setBackground(BaseConstant.COLOR_BGR_BASE);
		
		tableTree = new TableTree(this, SWT.FULL_SELECTION | SWT.BORDER);
		tableTree.setBounds(40, 166, 500, 262);
		tableTree.setFont(BaseConstant.FONT_BASE_LABEL);

		tblInfo = tableTree.getTable();
		tblInfo.addSelectionListener(new SelectionAdapter() {
			public void widgetDefaultSelected(final SelectionEvent arg0) {
				selectAction();
			}
		});
		tblInfo.setData(BaseConstant.TABLE_ROW_COUNT, Integer.toString(TBL_ROW_COUNT));
		tblInfo.setLinesVisible(true);
		tblInfo.setHeaderVisible(true);
		
		final TableColumn tcolFoodName = new TableColumn(tblInfo, SWT.NONE);
		tcolFoodName.setWidth(178);
		tcolFoodName.setText(LangResources.getText("SWTFoodSearch.tblInfo.tcolFoodName"));
		
		final TableColumn tcolPrice = new TableColumn(tblInfo, SWT.RIGHT);
		tcolPrice.setAlignment(SWT.RIGHT);
		tcolPrice.setWidth(90);
		tcolPrice.setText(LangResources.getText("SWTFoodSearch.tblInfo.tcolPrice"));
		
		final TableColumn tcolUnit = new TableColumn(tblInfo, SWT.NONE);
		tcolUnit.setWidth(85);
		
		final TableColumn tcolDescription = new TableColumn(tblInfo, SWT.RIGHT);
		tcolDescription.setAlignment(SWT.LEFT);
		tcolDescription.setWidth(125);
		tcolDescription.setText(LangResources.getText("SWTFoodSearch.tblInfo.tcolDescription"));

		final Label line2 = new Label(this, SWT.HORIZONTAL | SWT.SEPARATOR);
		line2.setBounds(0, 463, 585, 15);
		line2.setBackground(BaseConstant.COLOR_BGR_BASE);
		
		clblMessage = new CLabel(this, SWT.RIGHT | SWT.SHADOW_IN | SWT.BORDER);
		clblMessage.setAlignment(SWT.CENTER);
		clblMessage.setForeground(BaseConstant.COLOR_LINK_LABEL);
		clblMessage.setBounds(15, 483, 250, 25);
		clblMessage.setFont(BaseConstant.FONT_BOLD_LABEL);
		clblMessage.setBackground(BaseConstant.COLOR_BGR_LABEL);
		
		btnSelect = new Button(this, SWT.NONE);
		btnSelect.addFocusListener(new FocusAdapter() {
			public void focusGained(final FocusEvent arg0) {
				clblMessage.setText("");
			}
		});
		btnSelect.setBounds(440, 434, 100, 23);
		btnSelect.setFont(BaseConstant.FONT_BASE_BUTTON);
		btnSelect.setText(LangResources.getText("btnSelect"));
		btnSelect.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
		btnSelect.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				selectAction();
			}
		});

		btnClear = new Button(this, SWT.NONE);
		btnClear.addFocusListener(new FocusAdapter() {
			public void focusGained(final FocusEvent arg0) {
				clblMessage.setText("");
			}
		});
		btnClear.setBounds(354, 485, 100, 23);
		btnClear.setFont(BaseConstant.FONT_BASE_BUTTON);
		btnClear.setText(LangResources.getText("btnClear"));
		btnClear.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
		btnClear.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				clearAction();
			}
		});
		
		btnClose = new Button(this, SWT.NONE);
		btnClose.addFocusListener(new FocusAdapter() {
			public void focusGained(final FocusEvent arg0) {
				clblMessage.setText("");
			}
		});
		btnClose.setBounds(460, 485, 100, 23);
		btnClose.setFont(BaseConstant.FONT_BASE_BUTTON);
		btnClose.setText(LangResources.getText("btnClose"));
		btnClose.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
		btnClose.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				if (!closeAction(true)) {
					btnClose.setFocus();
				}
			}
		});
	}

	/**
	 * select action
	 *
	 */
	protected void selectAction() {

		try {
			TableTreeItem item = tableTree.getSelection()[0];
			MstFoodDTO food = (MstFoodDTO)item.getData(Const.ITEMID);
			if (null == food){
				MsgBoxUtils.errorMsgBox("errors.NOT_SELECTED_RECORD");
				btnSelect.setFocus();
				return;
			}
			
			setResult(food);
			
			this.closeAction(false);
			
		} catch (ClientException e) {
			log.error("FatalException.", e);
			fatalErrorMsgBox();
		}
	}
}
